<?php
namespace ImiApp\ApiServer\Controller;

use Imi\JWT\Facade\JWT;
use Imi\Controller\HttpController;
use Imi\JWT\Annotation\JWTValidation;
use Imi\Server\Route\Annotation\Route;
use Imi\Server\Route\Annotation\Action;
use Imi\Server\Route\Annotation\Controller;

/**
 * @Controller("/jwt/")
 */
class JWTController extends HttpController
{
    /**
     * 登录
     * 
     * @Action
     *
     * @param string $username
     * @param string $password
     * @return void
     */
    public function login($username, $password)
    {
        if('imi123' === $username && '123456' === $password)
        {
            // 你需要往token里丢的数据
            $data = [
                'username'  =>  $username,
            ];
            $token = JWT::getToken($data);
            return [
                'success'   =>  true,
                'token'     =>  (string)$token,
            ];
        }
        else
        {
            return [
                'success'   =>  false,
            ];
        }
    }

    /**
     * 登录状态
     * 
     * @Action
     * 
     * @return void
     */
    public function status($jwt)
    {
        /** @var \Lcobucci\JWT\Token $token */
        $token = JWT::parseToken($jwt);
        // $token = JWT::parseToken($jwt, 'a'); // 指定配置名称
        $data = $token->getClaim('data'); // 获取往token里丢的数据
        $username = $data->username ?? null;
        return [
            'isLogin'   =>  null !== $username,
            'username'  =>  $username,
        ];
    }

    /**
     * 登录状态2
     * 
     * @Action
     * 
     * @JWTValidation(tokenParam="token", dataParam="data")
     *
     * @param \Lcobucci\JWT\Token $token
     * @param \stdClass $data
     * @return array
     */
    public function status2($token = null, $data = null)
    {
        $username = $data->username ?? null;
        return [
            'isLogin'   =>  null !== $username,
            'username'  =>  $username,
        ];
    }

}
